package cc.iotkit.screen.dao;

import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.screen.dto.Period;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;

@Component
public class OnlineStatisticsRepositoryImpl implements OnlineStatisticsRepository{
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 示例：
     * 年：/screen/online_times/year/2024
     * 月：/screen/online_times/month/2024-06
     * 日：/screen/online_times/day/2024-07-21
     * @param period
     * @param date
     * @return
     */
    public List<Map<String,Object>> getStatistics(String period,String date){
        int limit=10;
        String sql="select a.*,c.`name` product_name,d.model,round((TIME_TO_SEC(a.online_times) MOD 86400) / 3600,0) AS hours from(\n" +
                "SELECT a.device_id,min(b.device_name)device_name,min(b.model_id)model_id,min(b.product_key)product_key,round(sum(online_times),0) online_times\n" +
                "FROM `device_daily_report`  a\n" +
                "inner join device_info b on a.device_id=b.device_id\n" +
                "WHERE %s\n" +
                "GROUP BY device_id\n" +
                "ORDER BY online_times desc\n" +
                "limit %s\n" +
                ")a\n" +
                "left join product c on a.product_key=c.product_key\n" +
                "left join product_model d on d.id=a.model_id";
        String where=tenantPermission();
        if(period.equals(Period.Type.year.toString())){
            sql=String.format(sql,"year(report_date)="+date+where,limit);
        }else if(period.equals(Period.Type.month.toString())){
            sql=String.format(sql,"DATE_FORMAT(report_date,'%Y-%m')='"+date+"'"+where,limit);
        }else if(period.equals(Period.Type.day.toString())){
            sql=String.format(sql,"DATE_FORMAT(report_date,'%Y-%m-%d')='"+date+"'"+where,limit);
        }
        List<Map<String,Object>> result= entityManager.createNativeQuery(sql).unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .getResultList();
        return result;
    }

    private String tenantPermission(){
        //超级管理员或系统进程调用
        if(LoginHelper.isSuperAdmin()|| RequestContextHolder.getRequestAttributes()==null)
            return "";
        else {
            return " and b.tenant_id="+LoginHelper.getTenantId();
        }
    }
}
